package com.yonyou.crm.sprc.opportunity.ctrl;

import com.yonyou.crm.base.doc.rmitf.IBaseDocRmService;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sprc.opportunity.entity.OpportunityBVO;
import com.yonyou.crm.sprc.opportunity.entity.OpportunityVO;
import com.yonyou.crm.sprc.opportunity.rmitf.IOpportunityRmService;
import com.yonyou.crm.sprc.oppstage.rmitf.IOppstageRmService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/sprc/opportunities")
public class OpportunityCtrl {

    @Autowired
    private IOpportunityRmService service;

    @Autowired
    private IBaseDocRmService baseDocRmService;

    @Autowired
    private IOppstageRmService oppstageServece;

    /**
     * 获取筛选条件：商机类型、商机阶段、商机来源
     * @param request
     * @param response
     * @return
     * @throws CrmMessageException
     */
    @RequestMapping(value="condition" ,method = RequestMethod.GET)
    public Object getFilterConditon(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
        //目前不需要参数
        //JSONObject paramObj = RequestUtil.getParamObject(request);

        @SuppressWarnings("unchecked")
        Map<String,Object> filterConditonMap = service.getFilterConditon();

        return ResponseUtil.getObject(filterConditonMap);
    }

    /**
     * 查询商机
     *
     * @param request
     * @param response
     * @return
     * @throws CrmMessageException
     */

    @RequestMapping(method = RequestMethod.GET)
    public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

        JSONObject paramObj = RequestUtil.getParamObject(request);

        @SuppressWarnings("unchecked")
        Page<OpportunityVO> opportunityPage = service.getList(getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));

        return ResponseUtil.getObject(opportunityPage);
    }

    /**
     * 商机销售漏斗
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "funnel", method = RequestMethod.GET)
    public Object getFunnel(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

        JSONObject paramObj = RequestUtil.getParamObject(request);

        @SuppressWarnings("unchecked")
        List<Map<String,Object>> funnelData = service.getFunnel((Map<String, Object>)paramObj.get("searchMap"));
        Map<String,Object> map = service.getFunnelMoney((Map<String, Object>)paramObj.get("searchMap"));
        JSONObject result = new JSONObject();
        result.put("data", funnelData);
        result.put("money", map);
        return ResponseUtil.getObject(result);
    }

    /**
     * 商机详情
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public Object detail(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response)
            throws CrmMessageException {
        JSONObject paramObj = RequestUtil.getParamObject(request);
        if (id == null) {
            throw new CrmMessageException(PCCodeConstant.ServerError, "id不能为空");
        }
        OpportunityVO opportunityVO = service.getDetail(id);
        return ResponseUtil.getObject(opportunityVO);
    }

    /**
     * 点击完成动作
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "finishaction", method = RequestMethod.PUT)
    public Object finishAction(HttpServletRequest request, HttpServletResponse response)
            throws CrmMessageException {
        JSONObject paramObj = RequestUtil.getParamObject(request);
        Map<String,Object> paramMap = (Map<String, Object>)paramObj.get("paramMap");
        service.finishAction(paramMap);
        return ResponseUtil.getObject(null);
    }

    /**
     * 设置为当前阶段
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "setCurrentStage", method = RequestMethod.PUT)
    public Object setCurrentStage(HttpServletRequest request, HttpServletResponse response)
            throws CrmMessageException {
        JSONObject paramObj = RequestUtil.getParamObject(request);
        Map<String,Object> paramMap = (Map<String, Object>)paramObj.get("paramMap");
//        SimpleDateFormat fm = new SimpleDateFormat("YYYY-mm-dd hh:mm:ss");
//        String date = fm.format(new Date());
//        paramMap.put("stageStartTime",date);
        service.setCurrentStage(paramMap);
        return ResponseUtil.getObject(null);
    }


    /**
     * 商机结果获取
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "result/{id}", method = RequestMethod.GET)
    public Object result(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response)
            throws CrmMessageException {
        JSONObject paramObj = RequestUtil.getParamObject(request);
        if (id == null) {
            throw new CrmMessageException(PCCodeConstant.ServerError, "id不能为空");
        }
        List<Map<String,Object>> actionList = service.getResultById(id);
        List<Map<String,Object>> stageList = service.getStageById(id);

        List<Map<String,Object>> resultData = new ArrayList<Map<String,Object>>();
        for(int i=0;i<actionList.size();i++){
            //是否已有当前阶段
           boolean flag1 = false;
           for(int j=0;j<resultData.size();j++){
               if(actionList.get(i).get("oppstage_id").equals(resultData.get(j).get("oppstage_id"))){
                   flag1 = true;
                   List<Map<String,Object>> dimensionList = (List<Map<String,Object>>)resultData.get(j).get("children");
                   //是否已有当前维度
                   boolean flag2 = false;
                   for(int k=0;k<dimensionList.size();k++){
                       List<Map<String,Object>> actionsList = (List<Map<String,Object>>)dimensionList.get(k).get("children");
                       if(actionList.get(i).get("oppdimension_id").equals(dimensionList.get(k).get("oppdimension_id"))){
                           flag2 = true;
                           actionsList.add(actionList.get(i));
                           dimensionList.get(k).put("children",actionsList);
                           break;
                       }
                   }
                   if(flag2==false) {
                       Map<String, Object> map = new HashMap<String, Object>();
                       map.put("oppdimension_id", actionList.get(i).get("oppdimension_id"));
                       map.put("oppdimension_name", actionList.get(i).get("oppdimension_name"));
                       List<Map<String,Object>> actionsList = new ArrayList<Map<String,Object>>();
                       actionsList.add(actionList.get(i));
                       map.put("children",actionsList);
                       dimensionList.add(map);
                       resultData.get(j).put("children",dimensionList);
                   }else{
                       resultData.get(j).put("children",dimensionList);
                       break;
                   }
               }
           }
           if(flag1==false) {
               Map<String, Object> map = new HashMap<String, Object>();
               map.put("oppstage_id", actionList.get(i).get("oppstage_id"));
               map.put("oppstage_name", actionList.get(i).get("oppstage_name"));
               List<Map<String,Object>> dimensionList = new ArrayList<Map<String,Object>>();
               Map<String, Object> dimensionMap = new HashMap<String, Object>();
               dimensionMap.put("oppdimension_id", actionList.get(i).get("oppdimension_id"));
               dimensionMap.put("oppdimension_name", actionList.get(i).get("oppdimension_name"));
               List<Map<String,Object>> actionsList = new ArrayList<Map<String,Object>>();
               actionsList.add(actionList.get(i));
               dimensionMap.put("children",actionsList);
               dimensionList.add(dimensionMap);
               map.put("children", dimensionList);
               resultData.add(map);
           }
        }
        JSONObject data = new JSONObject();
        data.put("resultList",resultData);
        data.put("stageList",stageList);
        return ResponseUtil.getObject(data);
    }

    private OpportunityVO getOpportunityVO(HttpServletRequest request) {

        Map<String, Class<?>> fieldClassMap = new HashMap<String, Class<?>>();
        fieldClassMap.put("childList", OpportunityBVO.class);
        return RequestUtil.getVO(request, OpportunityVO.class, fieldClassMap);
    }

    /**
     * 新增商机
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public Object insert(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

        OpportunityVO opportunity = getOpportunityVO(request);

        String validMsg = insertValidator(opportunity);
        if (!validMsg.equals("")) {
            throw new CrmMessageException(validMsg);
        }
        List<Map<String,Object>> stageList = service.getStageBybiztype(opportunity.getType());
        List<Map<String,Object>> actionList = service.getActionBybiztype(opportunity.getType());
        opportunity = service.insert(opportunity,stageList,actionList);

        if (opportunity.getId() == null) {
            throw new CrmMessageException(PCCodeConstant.ServerError, "获取自增主键为空");
        }

        return ResponseUtil.getObject(opportunity);
    }
    /**
     * 商机新增校验
     *
     * @param opportunity
     *
     * @return String
     */

    private String insertValidator(OpportunityVO opportunity) {

        if (opportunity == null) {
            return "转换实体失败";
        }

        if (!StringUtils.isNotBlank(opportunity.getName())) {
            return "商机名称不能为空";
        }

        return "";
    }

    /**
     * 修改商机
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public Object update(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response)
            throws CrmMessageException {

        OpportunityVO opportunity =  getOpportunityVO(request);
        if (opportunity == null) {
            throw new CrmMessageException(PCCodeConstant.ServerError, "转换实体失败");
        }
        opportunity.setId(id);
        String validMsg = updateValidator(opportunity);
        if (!validMsg.equals("")) {
            throw new CrmMessageException(validMsg);
        }

        OpportunityVO newBrand = service.update(opportunity);

        return ResponseUtil.getObject(newBrand);
    }
    /**
     * 商机编辑校验
     *
     * @param opportunity
     *
     * @return String
     */

    private String updateValidator(OpportunityVO opportunity) {

        if (opportunity == null) {
            return "转换实体失败";
        }

        if (!StringUtils.isNotBlank(opportunity.getName())) {
            return "商机名称不能为空";
        }

        return "";
    }


    /**
     * 批量删除商机
     *
     * @param request
     * @param response
     * @return
     */

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "batch", method = RequestMethod.DELETE)
    public Object batchDelete(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

        JSONObject paramObj = RequestUtil.getParamObject(request);
        String idsStr = paramObj.getString("ids");

        if (idsStr == null) {
            throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
        }

        String[] idArray = idsStr.split(",");

        if (idArray.length == 0) {
            throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
        }

        Map<String, Object> deleteResult = service.batchDelete(idArray, getRequestPage(paramObj), (Map<String, Object>) paramObj.get("searchMap"));
        return ResponseUtil.getObject(deleteResult.get("page"), PCCodeConstant.Success,deleteResult.get("message").toString());
    }


    /**
     * 获取分页信息
     * @param paramObj
     * @return Page<OpportunityBVO>
     */
    private Page<OpportunityVO> getRequestPage(JSONObject paramObj) throws CrmMessageException {

        Integer page = paramObj.getInt(HttpKeyConstant.Page);
        Integer pageSize = paramObj.getInt(HttpKeyConstant.PageSize);

        if (page == null) {
            throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
        }

        if (pageSize == null) {
            throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
        }

        return new Page<OpportunityVO>(page, pageSize);
    }


    /**
     * 商机赢单
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "winOpp/{id}", method = RequestMethod.PUT)
    public Object winOpp(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response)
            throws CrmMessageException {

        OpportunityVO vo = RequestUtil.getVO(request, OpportunityVO.class);
        vo.setId(id);
        OpportunityVO newVo =service.winOpp(vo);
        return ResponseUtil.getObject(newVo);
    }


    /**
     * 商机丢单
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "lostOpp/{id}", method = RequestMethod.PUT)
    public Object lostOpp(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response)
            throws CrmMessageException {

        OpportunityVO vo = RequestUtil.getVO(request, OpportunityVO.class);
        vo.setId(id);
        OpportunityVO newVo = service.lostOpp(vo);
        return ResponseUtil.getObject(newVo);
    }



    /**
     * 根据ID数组返回档案信息和档案详情
     * @param request
     * @param response
     * @return
     * @throws CrmMessageException
     */
    @RequestMapping(value = "winReason", method = RequestMethod.GET)
    public Object getWinReason(HttpServletRequest request, HttpServletResponse response)
            throws CrmMessageException {

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("15","winReason");
        Map baseDocList = baseDocRmService.getDocAndDetailList(map);
        JSONObject result = new JSONObject();
        result.put("data", baseDocList);
        return ResponseUtil.getObject(result);
    }

    /**
     * 根据ID数组返回档案信息和档案详情
     * @param request
     * @param response
     * @return
     * @throws CrmMessageException
     */
    @RequestMapping(value = "lostReason", method = RequestMethod.GET)
    public Object getLostReason(HttpServletRequest request, HttpServletResponse response)
            throws CrmMessageException {

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("16","lostReason");
        Map baseDocList = baseDocRmService.getDocAndDetailList(map);
        JSONObject result = new JSONObject();
        result.put("data", baseDocList);
        return ResponseUtil.getObject(result);
    }
}
